const request = require('../../utils/request');
const { getUserLocation } = require('../../utils/location');

const STATUS_TEXT = {
  1: '已接单',
  2: '已取件',
  3: '送达中',
  4: '已完成',
  5: '已完成',
  6: '已取消'
};

Page({
  data: {
    currentTab: 0,
    orderFilter: 'all',
    isAcceptingOrders: true,
    showAcceptModal: false,
    selectedOrder: null,
    courierProfileId: null,

    locationFilters: ['全部区域', '宿舍区', '教学区', '食堂区', '图书馆'],
    selectedLocationIndex: 0,
    selectedLocation: '全部区域',

    sortOptions: ['默认排序', '价格最高', '距离最近', '最新发布'],
    selectedSortIndex: 0,
    selectedSort: '默认排序',

    priceFilter: 'all',

    userInfo: {
      id: '',
      nickname: '',
      studentId: '',
      avatarUrl: ''
    },

    creditScore: 100,
    creditTrend: 'flat',
    creditChange: 0,

    totalIncome: 0,
    availableBalance: 0,
    todayIncome: 0,
    monthIncome: 0,

    performanceStats: {
      totalOrders: 0,
      completedOrders: 0,
      avgRating: 0,
      completionRate: 0
    },

    availableOrders: [],
    myOrders: [],
    filteredMyOrders: [],
    pendingOrdersCount: 0,

    page: 1,
    pageSize: 10,
    hasMore: true,
    loadingAvailableOrders: false,
    loadingMyOrders: false
  },

  onLoad() {
    this.ensureLogin();
    this.refreshData();
  },

  onShow() {
    this.refreshData();
  },

  ensureLogin() {
    const userId = this.getUserId();
    if (!userId) {
      wx.reLaunch({ url: '/pages/login/login' });
    }
  },

  getUserId() {
    return wx.getStorageSync('userId');
  },

  async loadCourierData() {
    const userId = this.getUserId();
    if (!userId) return;

    try {
      let courierRes = await request({ url: `/api/couriers/${userId}` });

      // 如果当前用户还没有代拿员档案，则自动申请一个最简档案
      if (!courierRes.success || !courierRes.data) {
        try {
          const applyRes = await request({
            url: '/api/users/apply-courier',
            method: 'POST',
            data: { user_id: userId, student_id: '' }
          });
          if (applyRes && applyRes.success && applyRes.data) {
            courierRes = { success: true, data: applyRes.data };
          }
        } catch (e) {
          console.warn('自动创建代拿员身份失败:', e);
        }
      }

      if (courierRes.success && courierRes.data) {
        const courier = courierRes.data || {};
        const avatarPath = courier.avatar_url || '';
        this.setData({
          userInfo: {
            id: courier.user_id || userId,
            nickname: courier.nickname || courier.real_name || '代拿员',
            studentId: courier.student_id || '',
            avatarUrl: avatarPath ? request.buildUrl(avatarPath) : ''
          },
          courierProfileId: courier.id || null,
          isAcceptingOrders: courier.status === 1 || courier.isAccepting || false
        });
      }

      const [credit, income, performance] = await Promise.all([
        request({ url: `/api/couriers/credit/${userId}` }),
        request({ url: `/api/couriers/income/${userId}` }),
        request({ url: `/api/couriers/performance/${userId}` })
      ]);

      if (credit.success) {
        this.setData({
          creditScore: credit.data.score || 100,
          creditTrend: credit.data.trend || 'flat',
          creditChange: credit.data.change || 0
        });
      }

      if (income.success) {
        this.setData({
          totalIncome: income.data.total || 0,
          availableBalance: income.data.available || 0,
          todayIncome: income.data.today || 0,
          monthIncome: income.data.month || 0
        });
      }

      if (performance.success) {
        this.setData({ performanceStats: performance.data });
      }
    } catch (error) {
      console.error('加载代拿员数据失败:', error);
      wx.showToast({ title: '代拿员信息加载失败', icon: 'none' });
    }
  },

  async loadAvailableOrders(reset = false) {
    // 简化为一次性拉取所有待接订单（使用已有 /api/orders/available 接口）
    if (reset) {
      this.setData({
        page: 1,
        availableOrders: [],
        hasMore: false
      });
    }

    this.setData({ loadingAvailableOrders: true });

    try {
      const params = {
        page: 1,
        pageSize: 100
      };

      // 尝试获取当前位置，用于后端按距离排序（失败时仍可正常加载）
      try {
        const { latitude, longitude } = await getUserLocation();
        params.lat = latitude;
        params.lng = longitude;
      } catch (e) {
        console.warn('获取当前位置失败，按默认排序获取可接订单:', e);
      }

      const res = await request({
        url: '/api/orders/available',
        method: 'GET',
        data: params
      });

      let orders = [];
      if (res.success && res.data) {
        if (Array.isArray(res.data)) {
          orders = res.data;
        } else if (Array.isArray(res.data.orders)) {
          orders = res.data.orders;
        }
      }

      const userId = this.getUserId();

      // 先归一化，再过滤掉当前用户自己发布的订单
      const normalized = orders.map((o) => this.normalizeOrder(o));
      const withoutSelfOrders = normalized.filter(o => {
        const ownerId = o.order_user_id || o.order_user || o.user_id;
        return !ownerId || String(ownerId) !== String(userId);
      });

      const filteredAndSorted = this.applyOrderFilters(withoutSelfOrders);

      this.setData({
        availableOrders: filteredAndSorted,
        hasMore: false,
        loadingAvailableOrders: false
      });
    } catch (error) {
      console.error('加载可接订单失败:', error);
      this.setData({
        loadingAvailableOrders: false,
        availableOrders: reset ? [] : this.data.availableOrders
      });
    }
  },

  normalizeOrder(order) {
    const expectedTime = this.formatExpectedTime(order.delivery_time, order.note);

    return {
      ...order,
      id: order.id,
      finalFee: order.final_fee || order.suggested_fee || 0,
      pickupLocation: order.pickup_location,
      deliveryAddress: order.delivery_address,
      pickupCode: order.pickup_code,
      expressType: order.express_type || '未填写',
      expectedTime,
      createdAt: this.formatListTime(order.created_at),
      createdTimestamp: order.created_at ? new Date(order.created_at).getTime() : 0,
      // 优先使用后端提供的取件点到送达点的真实距离（distance_m），
      // 其次使用“代拿员到取件点”的距离，最后退回前端模拟值
      distance:
        (typeof order.distance_m === 'number' && order.distance_m > 0)
          ? order.distance_m
          : (typeof order.courier_distance_m === 'number' && order.courier_distance_m > 0
            ? order.courier_distance_m
            : this.calculateDistance()),
      isUrgent: order.urgency_level === 'urgent'
    };
  },

  // 根据当前筛选条件（区域、价格标签、排序方式）过滤并排序可接订单
  applyOrderFilters(orders) {
    let list = Array.isArray(orders) ? orders.slice() : [];

    // 1. 区域筛选：根据 pickupLocation/deliveryAddress 文本包含简单关键字
    const idx = this.data.selectedLocationIndex;
    const locationKeywords = ['', '宿舍', '教学', '食堂', '图书馆'];
    if (idx > 0 && idx < locationKeywords.length) {
      const kw = locationKeywords[idx];
      list = list.filter((o) => {
        const pick = (o.pickupLocation || '').toString();
        const drop = (o.deliveryAddress || '').toString();
        return pick.includes(kw) || drop.includes(kw);
      });
    }

    // 2. 排序：优先使用价格标签（高价优先/距离最近），否则使用下拉选择的排序方式
    const priceFilter = this.data.priceFilter;
    const sortIdx = this.data.selectedSortIndex;

    if (priceFilter === 'high') {
      list.sort((a, b) => (b.finalFee || 0) - (a.finalFee || 0));
    } else if (priceFilter === 'near') {
      list.sort((a, b) => (a.distance || 0) - (b.distance || 0));
    } else {
      // sortOptions: ['默认排序', '价格最高', '距离最近', '最新发布']
      switch (sortIdx) {
        case 1: // 价格最高
          list.sort((a, b) => (b.finalFee || 0) - (a.finalFee || 0));
          break;
        case 2: // 距离最近
          list.sort((a, b) => (a.distance || 0) - (b.distance || 0));
          break;
        case 3: // 最新发布
        case 0: // 默认排序 -> 也用最新发布
        default:
          list.sort((a, b) => (b.createdTimestamp || 0) - (a.createdTimestamp || 0));
          break;
      }
    }

    return list;
  },

  async loadMyOrders() {
    const userId = this.getUserId();
    if (!userId) return;

    this.setData({ loadingMyOrders: true });

    try {
      const res = await request({ url: `/api/orders/courier/${userId}`, method: 'GET' });
      let orders = [];
      if (res.success && res.data) {
        if (Array.isArray(res.data)) {
          orders = res.data;
        } else if (Array.isArray(res.data.orders)) {
          orders = res.data.orders;
        }
      }

      const mapped = orders.map((order) => ({
        ...order,
        finalFee: order.final_fee || order.suggested_fee || 0,
        pickupLocation: order.pickup_location,
        deliveryAddress: order.delivery_address,
        pickupCode: order.pickup_code,
        expectedTime: this.formatExpectedTime(order.delivery_time),
        statusText: STATUS_TEXT[order.status] || '未知状态',
        acceptedAt: this.formatClockTime(order.accepted_at),
        orderUserInfo: order.order_user_info || {}
      }));

      const pendingCount = mapped.filter(item => [1, 2, 3].includes(item.status)).length;

      this.setData({
        myOrders: mapped,
        filteredMyOrders: this.filterMyOrders(mapped, this.data.orderFilter),
        pendingOrdersCount: pendingCount,
        loadingMyOrders: false
      });
    } catch (error) {
      console.error('加载我的接单失败:', error);
      this.setData({ loadingMyOrders: false, myOrders: [], filteredMyOrders: [] });
      wx.showToast({ title: '接单记录加载失败', icon: 'none' });
    }
  },

  filterMyOrders(orders, filter) {
    if (filter === 'all') return orders;
    const statusMap = {
      accepted: [1],
      picked_up: [2],
      delivering: [3],
      completed: [4, 5]
    };
    return orders.filter(order => (statusMap[filter] || []).includes(order.status));
  },

  setOrderFilter(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      orderFilter: filter,
      filteredMyOrders: this.filterMyOrders(this.data.myOrders, filter)
    });
  },

  switchTab(e) {
    const tab = Number(e.currentTarget.dataset.tab);
    this.setData({ currentTab: tab });
    if (tab === 0) {
      this.loadAvailableOrders(true);
    } else if (tab === 1) {
      this.loadMyOrders();
    }
  },

  onLocationFilterChange(e) {
    const index = Number(e.detail.value);
    this.setData({
      selectedLocationIndex: index,
      selectedLocation: this.data.locationFilters[index]
    });
    this.loadAvailableOrders(true);
  },

  onSortChange(e) {
    const index = Number(e.detail.value);
    this.setData({
      selectedSortIndex: index,
      selectedSort: this.data.sortOptions[index]
    });
    this.loadAvailableOrders(true);
  },

  setPriceFilter(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({ priceFilter: filter });
    this.loadAvailableOrders(true);
  },

  toggleAcceptingOrders(e) {
    const isAccepting = e ? e.detail.value : !this.data.isAcceptingOrders;
    const userId = this.getUserId();
    if (!userId) return;

    request({
      url: '/api/couriers/toggle-accepting',
      method: 'POST',
      data: { userId, isAccepting }
    }).then((res) => {
      if (res.success) {
        this.setData({ isAcceptingOrders: isAccepting });
        wx.showToast({ title: isAccepting ? '开始接单' : '暂停接单', icon: 'success' });
      } else {
        wx.showToast({ title: res.message || '操作失败', icon: 'none' });
      }
    }).catch(() => {
      wx.showToast({ title: '操作失败', icon: 'none' });
    });
  },

  acceptOrder(e) {
    if (!this.data.isAcceptingOrders) {
      wx.showToast({ title: '请先开启接单功能', icon: 'none' });
      return;
    }
    const orderId = e.currentTarget.dataset.orderId;
    const order = this.data.availableOrders.find(item => item.id === orderId);
    this.setData({ selectedOrder: order || null, showAcceptModal: true });
  },

  hideAcceptModal() {
    this.setData({ showAcceptModal: false, selectedOrder: null });
  },

  async confirmAcceptOrder() {
    if (!this.data.selectedOrder) return;
    const userId = this.getUserId();
    if (!userId) return;

    try {
      const res = await request({
        url: `/api/orders/${this.data.selectedOrder.id}/accept`,
        method: 'POST',
        data: {
          userId,
          courier_user_id: this.data.courierProfileId
        }
      });

      if (res.success) {
        wx.showToast({ title: '接单成功' });
        this.hideAcceptModal();
        this.refreshData();
      } else {
        wx.showToast({ title: res.message || '接单失败', icon: 'none' });
      }
    } catch (error) {
      console.error('接单失败:', error);
      wx.showToast({ title: '接单失败', icon: 'none' });
    }
  },

  confirmPickup(e) {
    const orderId = e.currentTarget.dataset.orderId;
    request({ url: `/api/orders/${orderId}/pickup`, method: 'POST' })
      .then((res) => {
        if (res.success) {
          wx.showToast({ title: '取件确认成功' });
          this.loadMyOrders();
        } else {
          wx.showToast({ title: res.message || '操作失败', icon: 'none' });
        }
      })
      .catch(() => wx.showToast({ title: '操作失败', icon: 'none' }));
  },

  notifyDelivery(e) {
    const orderId = e.currentTarget.dataset.orderId;
    request({ url: `/api/orders/${orderId}/deliver`, method: 'POST' })
      .then((res) => {
        if (res.success) {
          wx.showToast({ title: '已通知用户' });
          this.loadMyOrders();
        } else {
          wx.showToast({ title: res.message || '操作失败', icon: 'none' });
        }
      })
      .catch(() => wx.showToast({ title: '操作失败', icon: 'none' }));
  },

  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.orderId;
    const role = this.data.currentTab === 0 ? 'courier_view' : 'courier';
    wx.navigateTo({ url: `/pages/orderDetail/orderDetail?orderId=${orderId}&role=${role}` });
  },

  loadMoreOrders() {
    if (!this.data.hasMore) return;
    this.setData({ page: this.data.page + 1 });
    this.loadAvailableOrders();
  },

  calculateDistance() {
    return Math.floor(Math.random() * 600) + 200;
  },

  formatListTime(timeStr) {
    if (!timeStr) return '';
    const date = new Date(timeStr);
    return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  },

  formatClockTime(timeStr) {
    if (!timeStr) return '';
    const date = new Date(timeStr);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  },

  formatExpectedTime(timeStr, note) {
    // 优先使用后端 delivery_time 字段
    if (timeStr) {
      try {
        // 处理 "YYYY-MM-DD HH:MM:SS" 或 Date 对象等常见格式
        const d = typeof timeStr === 'string' ? new Date(timeStr.replace('T', ' ')) : new Date(timeStr);
        if (!Number.isNaN(d.getTime())) {
          const hh = String(d.getHours()).padStart(2, '0');
          const mm = String(d.getMinutes()).padStart(2, '0');
          return `${hh}:${mm}`;
        }
        const parts = String(timeStr).split(' ');
        if (parts.length > 1) return parts[1].slice(0, 5);
        return String(timeStr).slice(0, 5);
      } catch (e) {
        // ignore and fallback to note
      }
    }

    // 其次尝试从备注中解析“期望时间”信息
    if (note) {
      const m = String(note).match(/期望时间[段：:]*([^\n]+)/);
      if (m && m[1]) {
        return m[1].trim();
      }
    }

    return '';
  },

  goToIncome() {
    wx.navigateTo({ url: '/pages/income/income' });
  },

  goToPerformance() {
    wx.navigateTo({ url: '/pages/performance/performance' });
  },

  switchToOrderUser() {
    const app = getApp();
    app.switchRole('order_user');
  },

  switchToOrderHall() {
    this.setData({ currentTab: 0 });
    this.loadAvailableOrders(true);
  },

  editProfile() {
    wx.navigateTo({ url: '/pages/profile/editProfile' });
  },

  showSettings() {
    // 与下单者统一，进入同一个系统设置中心
    wx.navigateTo({ url: '/pages/profile/settingsCenter' });
  },

  showHelp() {
    // 代拿员端帮助中心，带上身份上下文
    wx.navigateTo({ url: '/pages/profile/helpCenter?context=courier' });
  },

  showFeedback() {
    wx.navigateTo({ url: '/pages/profile/feedback' });
  },

  showCreditRules() {
    wx.showModal({
      title: '代拿员信用分规则',
      content: `• 初始信用值：100分
• 未按时送达：-2分
• 差评：-1分
• 按时完成：+1分
• 好评：+2分`,
      showCancel: false
    });
  },

  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          wx.clearStorageSync();
          const app = getApp();
          app.globalData.userId = null;
          app.globalData.userRole = null;
          app.globalData.isLoggedIn = false;
          wx.reLaunch({ url: '/pages/login/login' });
        }
      }
    });
  },

  refreshData() {
    this.loadCourierData();
    if (this.data.currentTab === 0) {
      this.loadAvailableOrders(true);
    } else if (this.data.currentTab === 1) {
      this.loadMyOrders();
    }
  },

  onPullDownRefresh() {
    this.refreshData();
    setTimeout(() => wx.stopPullDownRefresh(), 800);
  }
});
